package com.hornsun.account.API;

import com.google.common.base.Preconditions;
import com.hornsun.domain.dbo.User;
import com.hornsun.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by 编译中... on 2018/1/27.
 */
@RestController
@RequestMapping("api/account")
public class AccountAPI {
    @Autowired
    private UserRepository userRepository;
    /**
     * 用户注册
     * @param user
     */
    @PostMapping("/addAccount")
    public ResponseEntity<?> addAccount(@RequestParam User user){
        if(user.getMobile()==null){
            throw new IllegalArgumentException("can not find mobile!");
        }
        user.setUserGuid(UUID.randomUUID().toString());
        user.setUsername(user.getMobile());
        user.setPassword("12345678");
        userRepository.insertUser(user);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 修改用户信息
     * @param newUser
     */
    @PostMapping("/updateAccount")
    public ResponseEntity<?> updateAccount(@RequestParam User newUser){
        userRepository.updateUser(newUser);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除用户
     * @param userName
     */
    @PostMapping("/deleteAccount")
    public ResponseEntity<?> deleteAccount(@RequestParam("userName") String userName){
        userRepository.deleteUser(userName);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 用户登陆
     * @param username
     * @param password
     * @return
     */
    @PostMapping(value = "/login")
    public ResponseEntity<User> longin(@RequestParam("username")String username, @RequestParam("password")String password){
        Preconditions.checkNotNull(username);
        Preconditions.checkNotNull(password);
        long count = userRepository.getCountByUsernameAndPassword(username,password);
        if(count==1){
            User user= userRepository.getUserByUsername(username);
            return new ResponseEntity<>(user,HttpStatus.OK);
        }else {
            throw new IllegalArgumentException("username or password not matching!");
        }

    }

    /**
     * 查询所有用户
     * @return
     */
    @GetMapping("/queryAllAccount")
    public ResponseEntity<List<User>> queryAllAccount(){
        List<User> list = userRepository.getAllAccount();
        return new ResponseEntity<>(list,HttpStatus.OK);
    }

}